package com.howard.action;

import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.danga.MemCached.MemCachedClient;
import com.howard.core.cache.MemCachedFactory;
import com.howard.entity.User;
import com.howard.exception.LoginException;
import com.howard.service.LoginService;
import com.howard.vo.Login;

/**
 * @author  <a href="mailto:howard.he0329@gmail.com">Howard He</a>
 *
 */
@Controller
public class LoginController {

	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

	private static final String PREFIX_LOGIN = "/login/";

	@Autowired
	private LoginService loginService;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return PREFIX_LOGIN + "login";
	}

	@RequestMapping(value= "/doLogin")
	public String doLogin(Login login, Model model, HttpServletRequest request) {
		try {
			User user = loginService.doLogin(login);
			if(user != null) {
				//用户信息放入到缓存中 MemCached存储用户信息做session用
				MemCachedClient client = MemCachedFactory.createMemCacheClient();
				String sid = null;
				if(!client.keyExists(sid = obtainSessionId(request)))
					client.add(sid, user, new Date(System.currentTimeMillis() + 30 * 1000));
				model.addAttribute(user);
			}
		} catch (LoginException e) {
			logger.error("doLogin", e);
			return PREFIX_LOGIN + "failed";
		}
		return PREFIX_LOGIN + "loginsuccess";
	}

	private String obtainSessionId(HttpServletRequest request) {
		String sessionId = null;
		for(Cookie c :request.getCookies()) {
			if(c.getName().equals("JSESSIONID")) {
				sessionId = c.getValue();
				break;
			}
		}
		if(logger.isDebugEnabled()) {
			logger.debug("JSESSIONID: " + StringUtils.substringBefore(sessionId, "."));
		}
		return StringUtils.substringBefore(sessionId, ".");
	}
}
